package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderService orderService;
    @Autowired
    OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("定时处理超时订单");
        //处理超时订单  如果当前状态为待支付状态的订单  修改为取消状态
        // 查询当前时间之前状态为待支付状态并且创建时间在当前时间之前 15min的订单

        //前15min
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
       List<Orders> ordersList = orderMapper.processTimeoutOrder(Orders.PAID,localDateTime);

       if(ordersList != null&& ordersList.size()>0){
           for (Orders orders : ordersList) {
               orders.setStatus(Orders.CANCELLED);
               orders.setCancelReason("支付超时");
               orders.setCancelTime(LocalDateTime.now());
               //修改订单状态为取消状态
               orderMapper.update(orders);
           }
       }
    }


    @Scheduled(cron = "0 0 1 * * ? ")
    //处理派送中的订单
    public void processDeliveryOrder(){
        log.info("定时处理派送中的订单");

        //查询派送中的订单 并且状态为4 DELIVERY_IN_PROGRESS并且时间在0点之前 统一在凌晨一点修改为5 COMPLETED
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.processTimeoutOrder(Orders.DELIVERY_IN_PROGRESS,localDateTime);
        if(ordersList != null&& ordersList.size()>0){
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                //修改订单状态为完成
                orderMapper.update(orders);
            }
        }

    }
}
